import threading
from login import use_default_login
from collect import WeChatClient
from generate import ReportGenerator
import utils
from datetime import date, timedelta, datetime
import os


# 查询发票信息
def main(month, thread = 8):
    month = utils.get_tomonth_unix(month)
    library = utils.default_library()
    service = use_default_login()
    account_chunks = library.get_account_chunks(thread)
    chunk_count = 1
    print('查询发票信息')
    for chunk in account_chunks:
        print('=第{}批线程开始='.format(chunk_count))
        pool = []
        for gh_id in chunk:
            account = library.get_account_data(gh_id)
            thread = GetInvoiceInfoThread(service, account, month)
            thread.start()
            pool.append(thread)
        for thread in pool:
            thread.join()
        print('=第{}/{}批线程结束='.format(chunk_count, len(account_chunks)))
        chunk_count += 1
    print('=生成发票报告=')
    reporter = ReportGenerator(library, utils.get_today())
    reporter.make_invoice()
    input('=运行结束，按回车键退出=')
    

class GetInvoiceInfoThread(threading.Thread):
    def __init__(self, service, account, month):
        threading.Thread.__init__(self)
        self.service = service
        self.account = account
        self.month = month

    def run(self):
        srv = WeChatClient(self.service)
        if not srv.enter(self.account['gh_id'], self.account['nickname'], self.account['pwd']):
            return
        self.account['nickname'], self.account['wx_id'], self.account['gs'] = srv.get_nickname_when_not()
        srv.save_basic_info(self.account, utils.get_today())
        srv.get_invoice_info(self.account['nickname'], self.month)

if __name__ == '__main__':
    os.makedirs('发票', exist_ok=True)
    month = input('> 请输入所需获取发票开始月份（默认为当月{}）: '.format(utils.get_tomonth()))
    main(month if month else utils.get_tomonth())
